package org.geektimes.projects.user.sql;

import org.geektimes.projects.user.domain.User;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class DBConnectionManager {
    static final String databaseURL = "jdbc:derby:D:\\workspace\\db;create=true";

    private DBConnectionManager(){}

    private static DataSource dataSource=new DataSource();

    private static Connection connection;

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        return dataSource.init();
    }

    private static class DataSource{
        private Connection init() throws SQLException, ClassNotFoundException {
            /**
             * {@link DriverManager#loadInitialDrivers()}
             * 该方法在static里面 loadInitialDrivers会在类加载时候调用,而 init()是懒加载所有,SPI和系统参数设置
             * 没有用
             *
             */
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            return DriverManager.getConnection(databaseURL);
        }
    }

    public void releaseConnection()     {
        if (this.connection != null) {
            try {
                this.connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getCause());
            }
        }
    }

    public static final String DROP_USERS_TABLE_DDL_SQL = "DROP TABLE users";

    public static final String CREATE_USERS_TABLE_DDL_SQL = "CREATE TABLE users(" +
            "id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
            "name VARCHAR(16) NOT NULL, " +
            "password VARCHAR(64) NOT NULL, " +
            "email VARCHAR(64) NOT NULL, " +
            "phoneNumber VARCHAR(64) NOT NULL" +
            ")";

    public static final String INSERT_USER_DML_SQL = "INSERT INTO users(name,password,email,phoneNumber) VALUES " +
            "('A','******','a@gmail.com','1') , " +
            "('B','******','b@gmail.com','2') , " +
            "('C','******','c@gmail.com','3') , " +
            "('D','******','d@gmail.com','4') , " +
            "('E','******','e@gmail.com','5')";



    /**
     * 数据类型与 ResultSet 方法名映射
     */
    static Map<Class, String> typeMethodMappings = new HashMap<>();

    public static void main(String[] args) throws IntrospectionException {

        //1 开始分析bean，2 停止object结束
        BeanInfo beanInfo = Introspector.getBeanInfo(User.class, Object.class);

    }
}
